package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.EmpInfo;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.EmpInfoMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.IEmpInfoService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class EmpInfoServiceImpl implements IEmpInfoService {

    @Autowired
    private EmpInfoMapper empInfoMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Value("${user.defaultPassword}")
    private String deafultPassword;

    @Value("${user.defaultRole}")
    private String defaultRole;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertEmpInfoBatch(List<EmpInfo> empList) {
        int rows = 0;
        SysUser sysUser = null;
        List<SysUser> userList = new ArrayList<>();
        String password = SecurityUtils.encryptPassword(deafultPassword);
        for (EmpInfo empInfo : empList) {
            String empNo = empInfo.getEmpNo();
            sysUser = new SysUser();
            sysUser.setUserId(empInfo.getEmpId());
            sysUser.setUserName(empNo);
            sysUser.setNickName(empInfo.getEmpName());
            sysUser.setEmail(empInfo.getEMail());
            sysUser.setPassword(password);
            if ("M".equals(empInfo.getGender())) {
                sysUser.setSex(UserConstants.USER_SEX_MALE);
            } else if ("F".equals(empInfo.getGender())) {
                sysUser.setSex(UserConstants.USER_SEX_FEMALE);
            } else {
                sysUser.setSex(UserConstants.USER_SEX_UNKNOWN);
            }
            if ("I".equalsIgnoreCase(empInfo.getHrStatus())) {
                sysUser.setDelFlag(UserConstants.USER_DEL);
            } else {
                sysUser.setDelFlag(UserConstants.NORMAL);
            }
            sysUser.setCreateBy("定时任务同步");
            //先删除一次默认角色，再插入
// 暂时不要                 userRoleMapper.deleteUserRoleInfo(new SysUserRole(sysUser.getUserId(),Long.valueOf(defaultRole)));
            // 暂时不要                userRoleMapper.insertUserRole(new SysUserRole(sysUser.getUserId(),Long.valueOf(defaultRole)));
            userList.add(sysUser);
        }
        rows += empInfoMapper.insertOrUpdateUser(userList);
        return rows;
    }

    @Override
    public void refreshUserRole() {
        empInfoMapper.refreshUserRole(defaultRole);
    }


}
